package org.example.fastproject.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.example.fastproject.core.exception.ApiException;

/**
 * @Author 王海舟
 * @Date 2023/2/2 12:23
 * @PackageName:org.example.fastproject.core.utils
 * @ClassName: JwtUtil
 * @Description: Jwt工具类
 * @Version 1.0
 */
public class JwtUtil {
    public static final String secret = "123456";

    /**
     * 获取token
     * @param userId
     * @return token
     */
    public static String getToken(Long userId) {
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("userId", userId);
        return builder.sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证token
     * @param token
     */
    public static Long validateToken(String token){
        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secret))
                    .build()
                    .verify(token);
            return decodedJWT.getClaim("userId").asLong();
        } catch (TokenExpiredException e){
            throw new ApiException("token已经过期");
        } catch (Exception e){
            throw new ApiException("token验证失败");
        }
    }
}
